<?php
declare(strict_types=1);

namespace app\common\service;

use app\common\model\Config;
use app\common\cache\ConfigCache;

class ConfigService
{

    /**
     * @notes 设置配置值
     * @param $type
     * @param $name
     * @param $value
     * @return mixed
     */
    public static function set(string $type, string $name, $value)
    {
        $original = $value;
        if (is_array($value)) {
            $value = json_encode($value, JSON_UNESCAPED_UNICODE);
        }

        $data = Config::where(['type' => $type, 'name' => $name])->findOrEmpty();
        if ($data->isEmpty()) {
            Config::create([
                'type' => $type,
                'name' => $name,
                'value' => $value,
            ]);
        } else {
            $data->value = $value;
            $data->save();
        }
        // 删除缓存
        $ConfigCache = new ConfigCache;
        $ConfigCache->deleteConfig($type);
        $ConfigCache->deleteConfig($type . '_' . $name);

        // 返回原始值
        return $original;
    }

    /**
     * @notes 获取配置值
     * @param $type
     * @param string $name
     * @param null $default_value
     * @return array|int|mixed|string
     */
    public static function get(string $type, string $name = '', $default_value = null)
    {
        $ConfigCache = new ConfigCache;
        if ($name) {
            $cacheValue = $ConfigCache->getConfig($type . '_' . $name);
            if ($cacheValue) return $cacheValue;

            $value = Config::where(['type' => $type, 'name' => $name])->value('value');
            if (!is_null($value)) {
                $json = json_decode($value, true);
                $value = json_last_error() === JSON_ERROR_NONE ? $json : $value;
            }
            if ($value || $value === 0 || $value === '0') {
                $ConfigCache->setConfig($type . '_' . $name, $value);
                return $value;
            }
            // 返回默认值
            if ($default_value !== null) {
                return $default_value;
            }
            // 返回本地配置文件中的值
            return config('project.' . $type . '.' . $name);
        }

        $cacheValue = $ConfigCache->getConfig($type);
        if ($cacheValue) return $cacheValue;

        // 取某个类型下的所有name的值
        $data = Config::where(['type' => $type])->column('value', 'name');
        foreach ($data as $k => $v) {
            $json = json_decode($v, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $data[$k] = $json;
            }
        }
        if ($data) {
            $ConfigCache->setConfig($type, $data);
            return $data;
        }
    }
}